﻿using System;
using System.IO;
using System.IO.Compression;

namespace Noria.Web.Utility
{
    internal static class NZip
    {
        public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName, bool overwrite = true)
        {
            if (sourceArchiveFileName == null)
            {
                throw new ArgumentNullException("sourceArchiveFileName");
            }
            using (ZipArchive source = ZipFile.Open(sourceArchiveFileName, ZipArchiveMode.Read, null))
            {
                if (source == null)
                {
                    throw new ArgumentNullException("source");
                }
                if (destinationDirectoryName == null)
                {
                    throw new ArgumentNullException("destinationDirectoryName");
                }

                // ?
                string fullName = Directory.CreateDirectory(destinationDirectoryName).FullName;

                foreach (ZipArchiveEntry entry in source.Entries)
                {
                    string fullPath = Path.GetFullPath(Path.Combine(fullName, entry.FullName));
                    if (!fullPath.StartsWith(fullName, StringComparison.OrdinalIgnoreCase))
                    {
                        throw new IOException("IO_ExtractingResultsInOutside");
                    }
                    if (Path.GetFileName(fullPath).Length == 0)
                    {
                        if (entry.Length != 0L)
                        {
                            throw new IOException("IO_DirectoryNameWithData");
                        }
                        Directory.CreateDirectory(fullPath);
                        continue;
                    }

                    Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
                    entry.ExtractToFile(fullPath, overwrite);
                }

            }
        }
    }
}